package com.ruoyi.zsyh.controller.applet.agent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CommonRpc;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 配件点Controller
 * 
 * @author yuexl
 * @date 2021-12-10
 */
@Controller
@RequestMapping("/applet/zsyh/partsStore")
public class ZsyhPartsStoreAppletController extends BaseController
{

    @Autowired
    private IZsyhUserPartsstoreService zsyhUserPartsstoreService;

    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;

    @Autowired
    private IZsyhUserRepairareaService zsyhUserRepairareaService;

    @Autowired
    private IZsyhPlatformUserService zsyhPlatformUserService;



    /**
     * 获取配件店 数值
     * @return
     */
    @RequestMapping("/getPartsStoreNum")
    @ResponseBody
    public AjaxResult getPartsStoreNum(String agentId)throws Exception
    {
        ZsyhUserRepairstore userPartsstore = new ZsyhUserRepairstore();
        userPartsstore.setAgentId(agentId);
        userPartsstore.setIsCity("0");
        userPartsstore.setIsAppraisal("0");
        List<ZsyhUserRepairstore> list1 = zsyhUserRepairstoreService.selectZsyhUserRepairstoreListApplet(userPartsstore);

        userPartsstore = new ZsyhUserRepairstore();
        userPartsstore.setAgentId(agentId);
        userPartsstore.setIsAppraisal("1");//是否打开鉴定权（1是0否）
        List<ZsyhUserRepairstore> list2 = zsyhUserRepairstoreService.selectZsyhUserRepairstoreListApplet(userPartsstore);

        userPartsstore = new ZsyhUserRepairstore();
        userPartsstore.setAgentId(agentId);
        userPartsstore.setIsCity("1");
        List<ZsyhUserRepairstore> list3 = zsyhUserRepairstoreService.selectZsyhUserRepairstoreListApplet(userPartsstore);



        Map map = new HashMap();
        map.put("num1", list1.size());//维修师傅
        map.put("num2", list2.size());//鉴定点
        map.put("num3", list3.size());//网点
        return success("成功", map);
    }

    /**
     * 获取接单点 维修师傅列表
     * @return
     */
    @RequestMapping("/getRepairStoreList")
    @ResponseBody
    public AjaxResult getRepairStoreList(String agentId, String key, String pageNum, String pageSize)throws Exception
    {
        ZsyhUserRepairstore userPartsstore = new ZsyhUserRepairstore();
        userPartsstore.setAgentId(agentId);
        Map map = new HashMap();
        map.put("name", key);
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        userPartsstore.setParams(map);
        List<ZsyhUserRepairstore> list = zsyhUserRepairstoreService.selectZsyhUserRepairstoreListApplet(userPartsstore);
        return success("成功", list);
    }

    /**
     * 获取 鉴定点列表
     * @param appraisalState 鉴定点 状态（0未申请 1待审核 2通过 3驳回）
     * @return
     */
    @RequestMapping("/getPartsStoreList")
    @ResponseBody
    public AjaxResult getPartsStoreList(String agentId, String key, String appraisalState, String pageNum, String pageSize)throws Exception
    {
        ZsyhUserRepairstore userPartsstore = new ZsyhUserRepairstore();
        userPartsstore.setAgentId(agentId);
        userPartsstore.setIsAppraisal("1");
        userPartsstore.setAppraisalState(appraisalState);
        Map map = new HashMap();
        map.put("name", key);
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        userPartsstore.setParams(map);
        return success("成功", zsyhUserRepairstoreService.selectZsyhUserRepairstoreListApplet(userPartsstore));
    }

    /**
     * 审核鉴定点鉴定点
     * @param appraisalState 鉴定点 状态（0未申请 1待审核 2通过 3驳回）
     * @return
     */
    @RequestMapping("/auditIsAppraisal")
    @ResponseBody
    @Transactional
    public AjaxResult auditIsAppraisal(String id, String appraisalState, String appraisalRejectReason)throws Exception
    {

        ZsyhUserRepairstore store = new ZsyhUserRepairstore();
        store.setId(id);
        store.setAppraisalState(appraisalState);
        store.setAppraisalRejectReason(appraisalRejectReason);
        if("2".equals(appraisalState)){//通过审核
            store.setIsAppraisal("1");

            ZsyhUserRepairstore _store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(id);
            String userId = _store.getUserId();
            ZsyhPlatformUser user = new ZsyhPlatformUser();
            user.setId(userId);
            user.setIsAppraisal("1");
            zsyhPlatformUserService.updateZsyhPlatformUser(user);
        }else{
            store.setAppraisalState("0");
        }
        zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store);



        return success("成功");
    }

    /**
     * 获取待审核配件店列表
     * @return
     */
    @RequestMapping("/getPartsStoreAuditList")
    @ResponseBody
    public AjaxResult getPartsStoreAuditList(String agentId)throws Exception
    {
        ZsyhUserRepairstore userPartsstore = new ZsyhUserRepairstore();
        userPartsstore.setAgentId(agentId);
        userPartsstore.setStoreState("1");
        userPartsstore.setStoreClassify("2");
        return success("成功", zsyhUserRepairstoreService.selectZsyhUserRepairstoreListApplet(userPartsstore));
    }

    /**
     * 审核配件店
     * @param state 2通过 3驳回
     * @return
     */
    @RequestMapping("/auditPartsStore")
    @ResponseBody
    @Transactional
    public AjaxResult auditPartsStore(String id, String state, String reject)throws Exception
    {

        ZsyhUserRepairstore store = new ZsyhUserRepairstore();
        store.setId(id);
        store.setStoreState(state);
        store.setStoreRejectReason(reject);
        zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store);

        return success("成功");
    }

    /**
     * 配件店详情
     * @return
     */
    @RequestMapping("/getPartsStoreDetails")
    @ResponseBody
    public AjaxResult getPartsStoreDetails(String id)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(id);
        String userId = store.getUserId();
//        ZsyhUserRaker raker = zsyhUserRakerService.selectZsyhUserRakerByUserId(userId);
//        if(raker != null){
//            String rakerId = raker.getId();
//            List<Map> list =  zsyhUserRakerService.selectZsyhUserRakerareaList(rakerId);
//            store.setUserRakeareaList(list);
//        }

        return success("成功", store);
    }

    /**
     * 配件店详情
     * @return
     */
    @RequestMapping("/getUserRakerDetails")
    @ResponseBody
    public AjaxResult getUserRakerDetails(String userId)throws Exception
    {
//        ZsyhUserRaker raker = zsyhUserRakerService.selectZsyhUserRakerByUserId(userId);

        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        if(store == null){
            store = new ZsyhUserRepairstore();
//            store.setStorePerson(raker.getRakerPerson());
//            store.setStorePhone(raker.getRakerPhone());
        }
        ZsyhUserRepairarea area = new ZsyhUserRepairarea();
        area.setRepairId(store.getId());
        area.setType("2");
        List<ZsyhUserRepairarea> areaList = zsyhUserRepairareaService.selectZsyhUserRepairareaList(area);

        store.setUserRakeareaList(areaList);
        return success("成功", store);
    }

    /**
     * 修改鉴定权限  升级为鉴定点
     * @param isAppraisal 是否有鉴定权限 1有 0没有
     * @return
     */
    @RequestMapping("/updateIsAppraisal")
    @ResponseBody
    @Transactional
    public AjaxResult updateIsAppraisal(String id, String isAppraisal, String storeName, String storeImage, String storeLicense, String storeAddress)throws Exception
    {

        ZsyhUserRepairstore store = new ZsyhUserRepairstore();
        store.setId(id);
        store.setIsAppraisal(isAppraisal);
        store.setStoreName(storeName);
        store.setStoreImage(storeImage);
        store.setStoreLicense(storeLicense);
        store.setStoreAddress(storeAddress);
        if("1".equals(isAppraisal)){
            store.setAppraisalState("2");//鉴定点 状态（0未申请 1待审核 2通过 3驳回）

            //修改用户 是否是鉴定点
            ZsyhUserRepairstore _store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(id);
            String userId = _store.getUserId();
            ZsyhPlatformUser user = new ZsyhPlatformUser();
            user.setId(userId);
            user.setIsAppraisal("1");
            zsyhPlatformUserService.updateZsyhPlatformUser(user);

        }else{
            store.setAppraisalState("0");
        }
        zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store);



        return success("成功");
    }

    /**
     * 升级为网点（如果区域areaJson是空，则取消网点）
     * @return
     */
    @RepeatSubmit
    @RequestMapping("/upgradeCityPartsStore")
    @ResponseBody
    @Transactional
    public AjaxResult upgradeCityPartsStore(String id, String areaJson)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(id);
        String userId = store.getUserId();
        ZsyhPlatformUser user = zsyhPlatformUserService.selectZsyhPlatformUserById(userId);

        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(areaJson, new TypeReference<List<Map<String, Object>>>() {});
        List<ZsyhUserRepairarea> areaList = new ArrayList<>();
        if(list.size() > 0){// 省级市县，或者修改管辖区域
//            ZsyhUserRaker raker = zsyhUserRakerService.selectZsyhUserRakerByUserId(userId);
//        ZsyhUserRaker raker = zsyhUserRakerService.selectZsyhUserRakerByPhone(store.getStorePhone());

            for(Map<String, Object> a:list){
                ZsyhUserRepairarea area = new ZsyhUserRepairarea();
                String pCode = String.valueOf(a.get("pCode"));
                String pName = String.valueOf(a.get("pName"));
                String cCode = String.valueOf(a.get("cCode"));
                String cName = String.valueOf(a.get("cName"));
                String aCode = String.valueOf(a.get("aCode"));
                String aName = String.valueOf(a.get("aName"));
                area.setId(IdWorker.getId());
                area.setCreateTime(new Date());
                area.setRepairId(id);
                area.setRepairProvince(pCode);
                area.setRepairProvinceName(pName);
                area.setRepairCity(cCode);
                area.setRepairCityName(cName);
                area.setRepairDistrict(aCode);
                area.setRepairDistrictName(aName);
                area.setType("2");
                areaList.add(area);
            }
            if(areaList.size() > 0){
                zsyhUserRepairareaService.deleteZsyhUserRepairareaByRepairId(id);//先删除原有的，然后再保存新的
                zsyhUserRepairareaService.insertZsyhUserRepairareaBatch(areaList);
            }

            ZsyhUserRepairstore store1 = new ZsyhUserRepairstore();
            store1.setId(id);
            store1.setIsRaker("1");
            store1.setStoreState("2");
            zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store1);

            ZsyhPlatformUser user1 = new ZsyhPlatformUser();
            user1.setId(userId);
            user1.setIsCity("1");
            zsyhPlatformUserService.updateZsyhPlatformUser(user1);
        }else{

            ZsyhUserRepairstore store1 = new ZsyhUserRepairstore();
            store1.setId(id);
            store1.setIsRaker("0");
            store1.setStoreState("0");
            zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store1);

            ZsyhPlatformUser user1 = new ZsyhPlatformUser();
            user1.setId(userId);
            user1.setIsCity("0");
            zsyhPlatformUserService.updateZsyhPlatformUser(user1);
        }


        return success("成功");
    }

    /**
     * 配件店升级为市县
     * @return
     */
    @RepeatSubmit
    @RequestMapping("/upgradeCityArea")
    @ResponseBody
    @Transactional
    public AjaxResult upgradeCityArea(String userId, String areaJson)throws Exception
    {
//        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(id);
//        String userId = store.getUserId();
        ZsyhPlatformUser user = zsyhPlatformUserService.selectZsyhPlatformUserById(userId);
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);

        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(areaJson, new TypeReference<List<Map<String, Object>>>() {});
        List<ZsyhUserRepairarea> areaList = new ArrayList<>();
        if(list.size() > 0){// 省级市县，或者修改管辖区域
//            ZsyhUserRaker raker = zsyhUserRakerService.selectZsyhUserRakerByUserId(userId);
//        ZsyhUserRaker raker = zsyhUserRakerService.selectZsyhUserRakerByPhone(store.getStorePhone());
            for(Map<String, Object> a:list){
                ZsyhUserRepairarea area = new ZsyhUserRepairarea();
                String pCode = String.valueOf(a.get("pCode"));
                String pName = String.valueOf(a.get("pName"));
                String cCode = String.valueOf(a.get("cCode"));
                String cName = String.valueOf(a.get("cName"));
                String aCode = String.valueOf(a.get("aCode"));
                String aName = String.valueOf(a.get("aName"));
                area.setId(IdWorker.getId());
                area.setCreateTime(new Date());
                area.setRepairId(store.getId());
                area.setRepairProvince(pCode);
                area.setRepairProvinceName(pName);
                area.setRepairCity(cCode);
                area.setRepairCityName(cName);
                area.setRepairDistrict(aCode);
                area.setRepairDistrictName(aName);
                area.setType("2");
                areaList.add(area);
            }
            if(areaList.size() > 0){
                zsyhUserRepairareaService.deleteZsyhUserRepairareaByRepairId(store.getId());//先删除原有的，然后再保存新的
                zsyhUserRepairareaService.insertZsyhUserRepairareaBatch(areaList);
            }

            if(store != null){
                ZsyhUserRepairstore store1 = new ZsyhUserRepairstore();
                store1.setId(store.getId());
                store1.setIsRaker("1");
                store1.setStoreState("2");
                zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store1);
            }

            ZsyhPlatformUser user1 = new ZsyhPlatformUser();
            user1.setId(userId);
            user1.setIsCity("1");
            zsyhPlatformUserService.updateZsyhPlatformUser(user1);
        }else{

            if(store != null){
                ZsyhUserRepairstore store1 = new ZsyhUserRepairstore();
                store1.setId(store.getId());
                store1.setIsRaker("0");
                store1.setStoreState("0");
                zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store1);
            }


            ZsyhPlatformUser user1 = new ZsyhPlatformUser();
            user1.setId(userId);
            user1.setIsCity("0");
            zsyhPlatformUserService.updateZsyhPlatformUser(user1);
        }


        return success("成功");
    }

    /**
     * 配件店取消升级为市县
     * @return
     */
    @RequestMapping("/cancelCityPartsStore")
    @ResponseBody
    @Transactional
    public AjaxResult cancelCityPartsStore(String id)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(id);
        String userId = store.getUserId();

        ZsyhUserRepairstore store1 = new ZsyhUserRepairstore();
        store1.setId(id);
        store1.setIsRaker("0");
        store1.setStoreState("0");
        zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store1);

        ZsyhPlatformUser user = new ZsyhPlatformUser();
        user.setId(userId);
        user.setIsCity("0");
        zsyhPlatformUserService.updateZsyhPlatformUser(user);

        return success("成功");
    }


    /**
     * 获取市县代理商列表  大区获取提成点列表
     * @return
     */
    @RequestMapping("/getUserRakerList")
    @ResponseBody
    public AjaxResult getUserRakerList(String agentId, String key, String pageNum, String pageSize)throws Exception
    {
        ZsyhUserRepairstore userPartsstore = new ZsyhUserRepairstore();
        userPartsstore.setAgentId(agentId);
        userPartsstore.setIsCity("1");
        Map map = new HashMap();
        map.put("name", key);
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        userPartsstore.setParams(map);
        return success("成功", zsyhUserRepairstoreService.selectZsyhUserRepairstoreListApplet(userPartsstore));
    }


    /**
     * 获取市县代理商详情
     * @return
     */
    @RequestMapping("/getUserRakerById")
    @ResponseBody
    public AjaxResult getUserRakerById(String id)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(id);
        String userId = store.getUserId();
        return success("成功", store);
    }


    /**
     * 修改市县级管辖区域
     * @return
     */
    @RequestMapping("/updateCityArea")
    @ResponseBody
    @Transactional
    public AjaxResult updateCityArea(String id, String areaJson)throws Exception
    {

        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(id);
        String userId = store.getUserId();
        ZsyhPlatformUser user = zsyhPlatformUserService.selectZsyhPlatformUserById(userId);

        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(areaJson, new TypeReference<List<Map<String, Object>>>() {});
        List<ZsyhUserRepairarea> areaList = new ArrayList<>();
        if(list.size() > 0){// 省级市县，或者修改管辖区域
//            ZsyhUserRaker raker = zsyhUserRakerService.selectZsyhUserRakerByUserId(userId);
//        ZsyhUserRaker raker = zsyhUserRakerService.selectZsyhUserRakerByPhone(store.getStorePhone());

            for(Map<String, Object> a:list){
                ZsyhUserRepairarea area = new ZsyhUserRepairarea();
                String pCode = String.valueOf(a.get("pCode"));
                String pName = String.valueOf(a.get("pName"));
                String cCode = String.valueOf(a.get("cCode"));
                String cName = String.valueOf(a.get("cName"));
                String aCode = String.valueOf(a.get("aCode"));
                String aName = String.valueOf(a.get("aName"));
                area.setId(IdWorker.getId());
                area.setCreateTime(new Date());
                area.setRepairId(id);
                area.setRepairProvince(pCode);
                area.setRepairProvinceName(pName);
                area.setRepairCity(cCode);
                area.setRepairCityName(cName);
                area.setRepairDistrict(aCode);
                area.setRepairDistrictName(aName);
                area.setType("2");
                areaList.add(area);
            }
            if(areaList.size() > 0){
                zsyhUserRepairareaService.deleteZsyhUserRepairareaByRepairId(id);//先删除原有的，然后再保存新的
                zsyhUserRepairareaService.insertZsyhUserRepairareaBatch(areaList);
            }

            ZsyhUserRepairstore store1 = new ZsyhUserRepairstore();
            store1.setId(id);
            store1.setIsRaker("1");
            store1.setStoreState("2");
            zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store1);

            ZsyhPlatformUser user1 = new ZsyhPlatformUser();
            user1.setId(userId);
            user1.setIsCity("1");
            zsyhPlatformUserService.updateZsyhPlatformUser(user1);
        }else{

            ZsyhUserRepairstore store1 = new ZsyhUserRepairstore();
            store1.setId(id);
            store1.setIsRaker("0");
            store1.setStoreState("0");
            zsyhUserRepairstoreService.updateZsyhUserRepairstoreApplet(store1);

            ZsyhPlatformUser user1 = new ZsyhPlatformUser();
            user1.setId(userId);
            user1.setIsCity("0");
            zsyhPlatformUserService.updateZsyhPlatformUser(user1);
        }
        return success("成功");
    }

}
